package com.xy.core.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.UrlPathHelper;

import com.xy.core.util.Constants;
import com.xy.manage.action.TmemberAction;
import com.xy.manage.model.Tmember;

/**
 * 
 * 权限过滤
 * 
 * 
 */
public class FrontContextInterceptor extends HandlerInterceptorAdapter {
	private static final Logger log = Logger
			.getLogger(FrontContextInterceptor.class);
	public static final String SITE_PARAM = "_site_id_param";
	public static final String SITE_COOKIE = "_site_id_cookie";
	public static final String PERMISSION_MODEL = "_permission_key";

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String uri =  new UrlPathHelper().getOriginatingRequestUri(request);
		if(uri.startsWith("/member/")){
			// 获得用户
			Tmember user = (Tmember) request.getSession().getAttribute(Constants.FRONT_AUTH_KEY);
			// 用户为null跳转到登陆页面
			if (user == null) {
				response.sendRedirect(getLoginUrl(request));
				return false;
			}
		}
		return true;
	}
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler, ModelAndView mav)
			throws Exception { }
	 
	private String getLoginUrl(HttpServletRequest request) {
		StringBuilder buff = new StringBuilder();
		if (loginUrl.startsWith("/")) {
			String ctx = request.getContextPath();
			if (!StringUtils.isBlank(ctx)) {
				buff.append(ctx);
			}
		}
		buff.append(loginUrl).append("?");
		buff.append("returnUrl").append("=").append(returnUrl);

		return buff.toString();
	}

	private boolean exclude(String uri) {
		if (excludeUrls != null) {
			for (String exc : excludeUrls) {
				if (exc.equals(uri)) {
					return true;
				}
			}
		}
		return false;
	}
 

	private String[] excludeUrls;

	private String loginUrl;
	private String returnUrl;

	public void setExcludeUrls(String[] excludeUrls) {
		this.excludeUrls = excludeUrls;
	}

	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}

	public void setReturnUrl(String returnUrl) {
		this.returnUrl = returnUrl;
	}

}